package com.wisdom.collect.modbus.facade;

import com.wisdom.collect.modbus.Modbus;
import com.wisdom.collect.modbus.io.AbstractModbusTransport;
import com.wisdom.collect.modbus.net.UDPMasterConnection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class ModbusUDPMaster extends AbstractModbusMaster {

    private static final Logger logger = LoggerFactory.getLogger(ModbusUDPMaster.class);

    private UDPMasterConnection connection;

    public ModbusUDPMaster(String addr) {
        this(addr, Modbus.DEFAULT_PORT);
    }

    public ModbusUDPMaster(String addr, int port) {
        this(addr, port, Modbus.DEFAULT_TIMEOUT);
    }

    public ModbusUDPMaster(String addr, int port, int timeout) {
        super();
        try {
            InetAddress slaveAddress = InetAddress.getByName(addr);
            connection = new UDPMasterConnection(slaveAddress);
            connection.setPort(port);
            connection.setTimeout(timeout);
        }
        catch (UnknownHostException e) {
            throw new RuntimeException("Failed to construct ModbusUDPMaster instance.", e);
        }
    }

    @Override
    public void connect() throws Exception {
        if (connection != null && !connection.isConnected()) {
            connection.connect();
            transaction = connection.getModbusTransport().createTransaction();
            setTransaction(transaction);
        }
    }

    @Override
    public void disconnect() {
        if (connection != null && connection.isConnected()) {
            connection.close();
            transaction = null;
            setTransaction(null);
        }
    }

    @Override
    public void setTimeout(int timeout) {
        super.setTimeout(timeout);
        if (connection != null) {
            connection.setTimeout(timeout);
        }
    }

    @Override
    public AbstractModbusTransport getTransport() {
        return connection == null ? null : connection.getModbusTransport();
    }
}